
/**
** \file       pipeline.c
**
** \brief      this function parse the pipeline rule
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse
**             and De Olivera Guillaume
**
** \version    0.8
**
** \date       26 Novembre 2010
**
*/

#include "rules.h"

static s_pipeline       *my_free(s_pipeline     *pipe)
{
  if (pipe != NULL)
  {
    free(pipe->no);
    pipe->no = NULL;

    free(pipe->next);
    pipe->next = NULL;

    free_cmd(pipe->cmd);
    pipe->cmd = NULL;
  }

  free(pipe);
  return (NULL);
}

static s_pipeline       *other_cmd(s_pipeline   *pipe)
{
  s_command             *tmp_cmd = pipe->cmd;

  while (g_data->lexer != NULL && strcmp(g_data->lexer->token->id, "|") == 0)
  {
    g_data->lexer = g_data->lexer->next;

    while (g_data->lexer != NULL && strcmp(g_data->lexer->token->id, "\n") == 0)
      g_data->lexer = g_data->lexer->next;

    tmp_cmd->next = calloc(1, sizeof (s_command));

    if (g_data->lexer == NULL || rule_command(tmp_cmd->next) == NULL)
      return (my_free(pipe));

    tmp_cmd = tmp_cmd->next;
  }

  pipe->next = my_free(pipe->next);
  return (pipe);
}

s_pipeline              *rule_pipeline(s_pipeline      *pipe)
{
  pipe->next = calloc(1, sizeof (s_pipeline));

  if (g_data->lexer == NULL)
    return (my_free(pipe));

  if (strcmp(g_data->lexer->token->id, "!") == 0)
  {
    pipe->no = calloc(1, sizeof (char) * 2);
    pipe->no[0] = '!';
    pipe->no[1] = '\0';
    g_data->lexer = g_data->lexer->next;
  }
  else
    pipe->no = NULL;

  pipe->cmd = calloc(1, sizeof (s_command));

  if (g_data->lexer == NULL || rule_command(pipe->cmd) == NULL)
    return (my_free(pipe));

  return (other_cmd(pipe));
}
